package com.itheima.filter;

import com.itheima.bean.Employee;
import com.itheima.bean.User;
import com.itheima.utils.MyBaseContext;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


@WebFilter("/*")
public class EmployeeFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //1.获取访问的请求路径映射
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        String s = req.getRequestURI();
        //2.判断请求地址是否包含，要释放资源的字断，包含则直接放行
        if(s.contains("login")||s.contains("images")||s.endsWith(".css")||s.endsWith(".js")
                ||s.contains("page")||s.contains("iconfont")||s.endsWith("ioc")||s.contains("sms")){
            chain.doFilter(request, response);
            return;
        }
        //3.获取登录时存储在session作用域中的employee对象
        HttpSession se = req.getSession();
        Employee e = (Employee) se.getAttribute("employee");
        //判断返回的employee对象是否为空，为空则表示，没有登录，则将其重定向到登录页面
        if (e!=null){
            //作用域得值不为null则表示用户已经登录，所以将作用域得值存入ThreadLocal中，方便后面公共字段进行操作
            MyBaseContext.setThreadLocal(e.getId());
            chain.doFilter(request, response);
            return;
        }
        //获取session作用域中存储的移动端用户对象
        User user = (User) req.getSession().getAttribute("user");
        //判端User对象是否为空，为空则表示没有登录账号，不能放行，将其重定向到登录页面
        if (user != null){
            //进入这里表示用户登录成功session作用域中有用户信息，将用户id存入ThreadLocal中，并直接放行
            MyBaseContext.setThreadLocal(user.getId());
            chain.doFilter(request, response);
            return;
        }
        //没有登录重定向到登录页面
        if (s.contains("front")){
            resp.sendRedirect("/front/page/login.html");
        }else {
            resp.sendRedirect("/backend/page/login/login.html");
        }
    }
}
